from schematics.models import Model
from schematics.types import (IntType, StringType)
from schematics.types.compound import ListType, ModelType
from schematics.exceptions import ValidationError

# from common.exceptions import BadRequestException
from . import const
from .dfenvs import DFEnvs


class Env(Model):

    df_server_image_tag = StringType(
        serialized_name='DF_SERVER_IMAGE_TAG', default="latest"
    )
    df_agent_image_tag = StringType(
        serialized_name='DF_AGENT_IMAGE_TAG', default="latest"
    )
    type = IntType(serialized_name='TYPE', required=True)
    instance_name = StringType(serialized_name='INSTANCE_NAME', required=True)


class Message(Model):
    env_uuid = StringType(serialized_name='ENV_UUID', required=True)
    action = IntType(serialized_name='ACTION', required=True)
    envs = ListType(ModelType(Env), serialized_name='ENVS', default=[])

    def validate_envs(self, data, value):
        if value and data["action"] == const.ACTION_DEPLOY:
            envs = DFEnvs(data["env_uuid"])
            envs = envs.get_all()
            redis_env_names = envs.keys()
            instance_names = []
            for env in value:
                env.validate()
                name = env.instance_name if env.type == const.ENV_TYPE_INSTANCE or data[
                    'env_uuid'
                ] in env.instance_name else f"{env.instance_name}-{data['env_uuid']}"
                if name in instance_names or name in redis_env_names:
                    raise ValidationError(f"instance_name: {name} duplicate")
                instance_names.append(name)
